package test_315;

import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 张杰
 * Date: 2022-03-16
 * Time: 15:05
 */
public class HashBuck {
    static class Node {
        public int key;
        public int val;
        public Node next;

        public Node (int key,int val) {
            this.key = key;
            this.val = val;
        }
    }

    public Node[] array;
    public int usedSize;
    //负载因子
    public static final double DEFAULT_LOAD_FACTOR = 0.75;

    public HashBuck() {
        this.array = new Node[10];
    }

    /* put方法
     * @author zj
     * @date 2022/3/16
     * @param key
     * @param val
    */
    public void put(int key,int val) {
        //1、找到key应该存放的位置
        int index = key % array.length;
        //2、遍历index对应的链表，看key是否存在，存在更新，不存在插入
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                cur.val = val;
                return;
            }
            cur = cur.next;
        }
        //没有这个元素的话，就使用头插法将这个元素插入链表
        Node node = new Node(key,val);
        node.next = array[index];
        array[index] = node;
        this.usedSize++;
        //如果用尾插法来实现，就需要判断是不是第一次插入

        //判断负载因子是否高于0.75
        if(loadFactor() > 0.75) {
            resize();//扩容，扩容牵扯的问题是array长度变化后整个index的值都会发生变化，需要重现建hash表
        }
    }
    private void resize() {
        Node[] newArray = new Node[array.length*2];
        for (int i = 0; i < array.length ; i++) {
            Node cur = array[i];
            while(cur != null) {
                int index = cur.key % newArray.length;//获取新下标
                //就是把cur这个节点，以头插/尾插的形式 插入到新的数组对应的下标的链表中
                Node curNext = cur.next;
                //尾插
                cur.next = newArray[index];
                newArray[index] = cur;
                cur = cur.next;
            }
        }
       array = newArray;
    }
    private double loadFactor() {
        return 1.0*usedSize/array.length;
    }

    /* 根据key获取val值
     * @author zj
     * @date 2022/3/16
     * @param key
     * @return int
    */
    public int get(int key) {
        int index = key % array.length;
        Node cur = array[index];
        while(cur != null) {
            if(cur.key == key) {
                return cur.val;
            }
            cur = cur.next;
        }
        return -1;
    }

    public static void main(String[] args) {
        HashBuck hashBuck = new HashBuck();
        hashBuck.put(1,1);
        hashBuck.put(12,12);
        hashBuck.put(3,3);
        hashBuck.put(6,6);
        hashBuck.put(2,2);
        hashBuck.put(11,11);
        hashBuck.put(7,7);
        hashBuck.put(8,8);
        System.out.println(hashBuck.get(11));
    }
}
